<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service;

use app\enum\CommonEnum;
use app\model\ClientAccountModel;
use app\service\client\AccountService;
use app\service\ocean\AdvertiserService;
use app\service\ocean\AppExtendService;
use app\service\ocean\AwemeListService;
use app\service\ocean\AwemeVideoService;
use app\service\ocean\NativeAnchorService;
use app\service\ocean\OptimizedGoalService;
use think\Exception;

class OeFetchService extends BaseService
{
    /**
     * 拉取应用分包.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function fetchAppExtend(string $advertiserId = ''): bool
    {
        // 请求接口
        $clientAccountInfo = self::_getClientAccountInfo($advertiserId);
        if ($clientAccountInfo) {
            // 查询app
            $AppExtendService = new AppExtendService();
            $appIds = $AppExtendService->getAppList($advertiserId);
            if ($appIds) {
                foreach ($appIds as $appId) {
                    $page = 0;
                    while (true) {
                        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                        if (! $token) {
                            return self::setError('token获取失败');
                        }
                        ++$page;
                        $result = $AppExtendService->getAppData($token, $advertiserId, $appId, $page);
                        if (! $result) {
                            $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'app_id' => $appId, 'page' => $page], 'response' => AdvertiserService::getError(0)];
                            //                            return self::setError('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======' . PHP_EOL);
                            break;
                        }
                        $list = $result['data']['list'];
                        if (count($list) == 0) {
                            break;
                        }
                        foreach ($list as $v) {
                            $v['parent_package_id'] = $appId;
                            $v['account_id'] = $clientAccountInfo['id'];
                            $dataInfo = $AppExtendService->getAppInfo($advertiserId, $clientAccountInfo['id'], $v['package_id'], $v['channel_id'], $appId);
                            if (! empty($dataInfo)) {
                                $AppExtendService->updateAdvertiserData($dataInfo['id'], $v);
                            } else {
                                $AppExtendService->insertAdvertiserData($advertiserId, $v);
                            }
                        }
                    }
                }
            }
        } else {
            return self::setError('账户数据不存在');
        }
        return true;
    }

    /**
     * 拉取抖音号.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function fetchAwemeList(string $advertiserId = ''): bool
    {
        // 请求接口
        $clientAccountInfo = self::_getClientAccountInfo($advertiserId);
        if ($clientAccountInfo) {
            // 查询app
            $AwemeListService = new AwemeListService();
            $page = 0;
            while (true) {
                $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                if (! $token) {
                    return self::setError('token获取失败');
                }
                ++$page;
                $result = $AwemeListService->getAppData($token, $advertiserId, $page);
                if (! $result) {
                    $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'page' => $page], 'response' => $AwemeListService::getError(0)];
                    return self::setError('error:' . json_encode($err, JSON_UNESCAPED_UNICODE));
                }
                $list = $result['data']['list'];
                if (count($list) == 0) {
                    break;
                }
                foreach ($list as $v) {
                    $v['account_id'] = $clientAccountInfo['id'];
                    $dataInfo = $AwemeListService->getAppInfo($advertiserId, $v['aweme_id']);
                    if (! empty($dataInfo)) {
                        $AwemeListService->updateAdvertiserData($dataInfo['id'], $v);
                    } else {
                        $AwemeListService->insertAdvertiserData($advertiserId, $v);
                    }
                }
            }
        } else {
            return self::setError('账户数据不存在');
        }
        return true;
    }

    /**
     * 同步获取可用优化目标.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function fetchOptimizedGoal(string $advertiserId = ''): bool
    {
        // 请求接口
        $clientAccountInfo = self::_getClientAccountInfo($advertiserId);
        if ($clientAccountInfo) {
            $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
            if (! $token) {
                return self::setError('token获取失败');
            }
            $OptimizedGoalService = new OptimizedGoalService();
            // 获取资产信息
            $assetsData = $OptimizedGoalService->getAssets($advertiserId);
            if ($assetsData) {
                foreach ($assetsData as $assets) {
                    if ($assets['asset_type'] == 'APP') {
                        $assetArr = json_decode($assets['app'], true);
                        $param = [
                            'landing_type' => 'APP',
                            'ad_type' => 'ALL',
                            'asset_type' => 'APP',
                        ];
                    } elseif ($assets['asset_type'] == 'THIRD_EXTERNAL') {
                        $assetArr = json_decode($assets['landing_pages'], true);
                        $param = [
                            'landing_type' => 'LINK',
                            'ad_type' => 'ALL',
                            'asset_type' => 'THIRDPARTY',
                        ];
                    }
                    if (! empty($assetArr)) {
                        foreach ($assetArr as $asset) {
                            $param['asset_id'] = $asset['asset_id'];
                            if ($assets['asset_type'] == 'APP') {
                                $param['app_type'] = $asset['app_type'];
                                $param['app_promotion_type'] = 'DOWNLOAD';
                            }
                            // 请求接口
                            $result = $OptimizedGoalService->getAppData($token, $advertiserId, $param);
                            if (! $result) {
                                $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId], 'response' => AdvertiserService::getError(0)];
                                return self::setError('error:' . json_encode($err, JSON_UNESCAPED_UNICODE));
                            }
                            $list = $result['data']['goals'];
                            if (count($list) == 0) {
                                break;
                            }
                            foreach ($list as $v) {
                                $v['account_id'] = $clientAccountInfo['id'];
                                $v['asset_id'] = $asset['asset_id'];
                                $v['asset_type'] = $param['asset_type'];
                                $v['landing_type'] = $param['landing_type'];
                                $v['ad_type'] = $param['ad_type'];
                                $v['app_type'] = ! empty($param['app_type']) ? $param['app_type'] : '';
                                $v['app_promotion_type'] = ! empty($param['app_promotion_type']) ? $param['app_promotion_type'] : '';
                                $dataInfo = $OptimizedGoalService->getAppInfo($advertiserId, $v);
                                if (! empty($dataInfo)) {
                                    $OptimizedGoalService->updateAdvertiserData($dataInfo['id'], $v);
                                } else {
                                    $OptimizedGoalService->insertAdvertiserData($advertiserId, $v);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            return self::setError('账户数据不存在');
        }
        return true;
    }

    /**
     * 同步账户下原生锚点.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @deprecated
     */
    public static function fetchNativeAnchor(string $advertiserId = ''): bool
    {
        // 请求接口
        $clientAccountInfo = self::_getClientAccountInfo($advertiserId);
        if ($clientAccountInfo) {
            // 查询app
            $NativeAnchorService = new NativeAnchorService();
            $page = 0;
            while (true) {
                $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                if (! $token) {
                    return self::setError('token获取失败');
                }
                ++$page;
                $result = $NativeAnchorService->getAppData($token, $advertiserId, $page);
                if (! $result) {
                    $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'page' => $page], 'response' => AdvertiserService::getError(0)];
                    return self::setError('error:' . json_encode($err, JSON_UNESCAPED_UNICODE));
                }
                $list = $result['data']['list'];
                if (count($list) == 0) {
                    break;
                }
                foreach ($list as $v) {
                    $v['account_id'] = $clientAccountInfo['id'];
                    $dataInfo = $NativeAnchorService->getAppInfo($advertiserId, $v['anchor_id']);
                    if (! empty($dataInfo)) {
                        $NativeAnchorService->updateAdvertiserData($dataInfo['id'], $v);
                    } else {
                        $NativeAnchorService->insertAdvertiserData($advertiserId, $v);
                    }
                }
            }
        } else {
            return self::setError('账户数据不存在');
        }
        return true;
    }

    /**
     * 同步获取抖音主页视频.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function fetchAwemeVideo(string $advertiserId = '', string $awemeId = ''): bool
    {
        try {
            // 请求接口
            $clientAccountInfo = self::_getClientAccountInfo($advertiserId);
            if ($clientAccountInfo) {
                // 查询app
                $AwemeVideoService = new AwemeVideoService();
                // 查询抖音
                if (! $awemeId) {
                    $awemeIds = $AwemeVideoService->getAwemeIds($advertiserId);
                } else {
                    $awemeIds = [$awemeId];
                }
                if ($awemeIds) {
                    foreach ($awemeIds as $awemeId) {
                        $page = 0;
                        while (true) {
                            $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                            if (! $token) {
                                return self::setError('token获取失败');
                            }
                            ++$page;
                            $result = $AwemeVideoService->getAppData($token, $advertiserId, $awemeId, $page);
                            if (! $result) {
                                $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'aweme_id' => $awemeId, 'page' => $page], 'response' => AdvertiserService::getError(0)];
                                return self::setError('error:' . json_encode($err, JSON_UNESCAPED_UNICODE));
                            }
                            $list = $result['data']['list'];
                            if (count($list) == 0) {
                                break;
                            }
                            foreach ($list as $v) {
                                $v['account_id'] = $clientAccountInfo['id'];
                                $v['aweme_id'] = $awemeId;
                                $dataInfo = $AwemeVideoService->getAppInfo($advertiserId, $awemeId, $v['video_id']);
                                if (! empty($dataInfo)) {
                                    $AwemeVideoService->updateAdvertiserData($dataInfo['id'], $v);
                                } else {
                                    $AwemeVideoService->insertAdvertiserData($advertiserId, $v);
                                }
                            }
                        }
                    }
                }
            } else {
                return self::setError('账户数据不存在');
            }
        } catch (Exception $e) {
            return self::setError($e->getMessage());
        }
        return true;
    }

    /**
     * 实时获取橙子落地页.
     */
    public static function getOrangeSite(string $advertiserId = '', string $externalAction = '', string $deepExternalAction = '', string $searchMode = '')
    {
        try {
            $data = [];
            // 请求接口
            $page = 0;
            while (true) {
                $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                if (! $token) {
                    return self::setError('token获取失败');
                }
                ++$page;
                $header = ['Access-Token' => $token];
                $params = [
                    'advertiser_id' => $advertiserId,
                    'page' => $page,
                    'page_size' => 50,
                    'filtering' => ['search_mode' => $searchMode],
                    'status' => 'SITE_ONLINE',
                    'optimize_goal' => ['external_action' => $externalAction],
                ];
                if ($deepExternalAction) {
                    $params['optimize_goal']['deep_external_action'] = $deepExternalAction;
                }
                $result = AdvertiserService::getOrangeSite($header, $params);
                if (! $result) {
                    $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'page' => $page], 'response' => AdvertiserService::getError(0)];
                    return self::setError('error:' . json_encode($err, JSON_UNESCAPED_UNICODE));
                }
                $list = $result['data']['list'];
                if (count($list) == 0) {
                    break;
                }
                $data = array_merge($data, $list);
            }
            return $data;
        } catch (Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取账户信息.
     * @param string $advertiserId 账户ID
     * @throws
     */
    private static function _getClientAccountInfo(string $advertiserId = ''): array
    {
        $info = (new ClientAccountModel())->where('advertiser_id', $advertiserId)->field(true)->find();
        if (! $info) {
            return [];
        }
        return $info->toArray();
    }
}
